﻿using AutoMapper;
using IOA.MES.Common;
using IOA.MES.DataAccess.Entity;
using IOA.MES.DataAccess.Enum;
using IOA.MES.DataAccess.VModel;
using IOA.Utils;
using System;
using System.Collections.Generic;
using System.Linq;

namespace IOA.MES.Business
{
    /// <summary>
    /// 车间管理（错误代码：134001）
    /// </summary>
    public class WorkshopMgr
    {
        private MESContext mesDb = new MESContext("MES");

        /// <summary>
        /// 获取车间对象
        /// </summary>
        /// <param name="workshopId">车间ID</param>
        /// <returns>车间对象</returns>
        public VWorkshop GetWorkshop(int workshopId)
        {
            var entity = mesDb.Workshops.FirstOrDefault(_ => _.PkId == workshopId && _.Valid);
            return Mapper.Map<VWorkshop>(entity);
        }

        /// <summary>
        /// 获取车间对象
        /// </summary>
        /// <param name="workshopCode">车间代码</param>
        /// <returns>车间对象</returns>
        public VWorkshop GetWorkshop(string workshopCode)
        {
            var entity = mesDb.Workshops.AsNoTracking().FirstOrDefault(_ => _.WorkshopCode == workshopCode && _.Valid);
            return Mapper.Map<VWorkshop>(entity);
        }

        /// <summary>
        /// 编辑车间
        /// </summary>
        /// <param name="model">车间对象</param>
        public void EditWorkshop(VWorkshop model)
        {

            if (model.PkId <= 0)
            {
                var exist = mesDb.Workshops.FirstOrDefault(_ => _.WorkshopName == model.WorkshopName && _.Valid);
                if (exist != null)
                {
                    throw new MultiLanBizException(134001);// "车间名称已存在，请更换其他名称");
                }
                model.CreateTime = DateTime.Now;
                model.ModifyBy = 0;
                var entity = Mapper.Map<Workshop>(model);
                mesDb.Workshops.Add(entity);
            }
            else
            {
                var exist = mesDb.Workshops.FirstOrDefault(_ => _.WorkshopName == model.WorkshopName && _.PkId != model.PkId && _.Valid);
                if (exist != null)
                {
                    throw new MultiLanBizException(134001);// "车间名称已存在，请更换其他名称");
                }
                var entity = mesDb.Workshops.FirstOrDefault(_ => _.PkId == model.PkId && _.Valid);
                if (entity == null)
                {
                    throw new MultiLanBizException(134002);// "车间不存在或已被删除，无法编辑");
                }
                entity.WorkshopCode = model.WorkshopCode;
                entity.WorkshopName = model.WorkshopName;
                entity.Status = model.Status;
                entity.ModifyBy = model.ModifyBy;
                entity.ModifyTime = DateTime.Now;
            }
            mesDb.SaveChanges();
        }

        /// <summary>
        /// 查询车间列表
        /// </summary>
        /// <param name="pageIndex">页面索引</param>
        /// <param name="pageSize">页面容量</param>
        /// <param name="total">总数</param>
        /// <param name="status">状态</param>
        /// <param name="workshopName">关键字</param>
        /// <returns>车间列表</returns>
        public List<VWorkshop> QueryWorkshops(int pageIndex, int pageSize, out int total, WorkshopStatus? status, string workshopName)
        {
            var query = mesDb.Workshops.Where(_ => _.Valid);
            if (status.HasValue)
            {
                query = query.Where(_ => _.Status == status.Value);
            }
            if (!string.IsNullOrWhiteSpace(workshopName))
            {
                query = query.Where(_ => _.WorkshopName.Contains(workshopName));
            }

            total = query.Count();
            query = query.OrderBy(_ => _.WorkshopName);
            var entities = pageSize <= 0 ? query.ToList() : query.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            var models = Mapper.Map<List<VWorkshop>>(entities);
            var workshopCodes = models.Select(_ => _.WorkshopCode).Distinct().ToList();
            var duties = mesDb.WorkshopDuties.Where(_ => workshopCodes.Contains(_.WorkshopCode) && _.Status == CommonStatus.Normal && _.Valid).ToList();
            var lines = mesDb.AssemblyLines.Where(_ => workshopCodes.Contains(_.WorkshopCode) && _.Status == CommonStatus.Normal && _.Valid).ToList();
            models.ForEach(workshop =>
            {
                workshop.DutyNames = string.Join("、", duties.Where(_ => string.Equals(_.WorkshopCode, workshop.WorkshopCode, StringComparison.CurrentCultureIgnoreCase)).Select(_ => _.DutyName));
                workshop.LineNames = string.Join("、", lines.Where(_ => string.Equals(_.WorkshopCode, workshop.WorkshopCode, StringComparison.CurrentCultureIgnoreCase)).Select(_ => _.LineName));
            });
            return models;
        }

        /// <summary>
        /// 查询用户车间列表
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns>车间列表</returns>
        public List<VWorkshop> QueryUserWorkshops(int userId)
        {
            var userRoles = (from userRole in mesDb.UserRoles.AsNoTracking().Where(_ => _.UserId == userId && _.Valid)
                             join role in mesDb.Roles.AsNoTracking().Where(_ => _.Valid) on userRole.RoleId equals role.PkId
                             select role).ToList();

            var query = mesDb.Workshops.AsNoTracking().Where(_ => _.Valid);
            if (!userRoles.Any(_ => new[] { 1 }.Contains(_.PkId)))
            {
                query = from workshop in query
                        join userWorkshop in mesDb.UserWorkshops.Where(_ => _.Valid && _.UserId == userId) on workshop.WorkshopCode equals userWorkshop.WorkshopCode
                        select workshop;
            }

            var entities = query.OrderBy(_ => _.WorkshopName).ToList();
            var models = Mapper.Map<List<VWorkshop>>(entities);

            var workshopCodes = models.Select(_ => _.WorkshopCode).Distinct().ToList();
            var lines = !workshopCodes.Any() ? new List<AssemblyLine>()
                : mesDb.AssemblyLines.AsNoTracking().Where(_ => workshopCodes.Contains(_.WorkshopCode) && _.Valid).ToList();
            models.ForEach(model =>
            {
                model.Lines = Mapper.Map<List<VAssemblyLine>>(lines.Where(_ => StringUtils.Equals(_.WorkshopCode, model.WorkshopCode)).ToList());
            });
            return models;
        }

        /// <summary>
        /// 查询车间列表
        /// </summary>
        /// <param name="workshopCodes">车间代码列表</param>
        /// <returns>车间列表</returns>
        public List<VWorkshop> QueryWorkshops(List<string> workshopCodes)
        {
            var entities = !workshopCodes.Any() ? new List<Workshop>() : mesDb.Workshops.AsNoTracking().Where(_ => workshopCodes.Contains(_.WorkshopCode) && _.Valid).ToList();
            return Mapper.Map<List<VWorkshop>>(entities);
        }

        /// <summary>
        /// 获取车间FTP配置
        /// </summary>
        /// <param name="workshopCode">车间代码</param>
        /// <returns></returns>
        public VFtpConfig GetFtpConfig(string workshopCode)
        {
            var entity = mesDb.FtpConfigs.AsNoTracking().FirstOrDefault(_ => _.WorkshopCode == workshopCode && _.Valid);
            return Mapper.Map<VFtpConfig>(entity);
        }
    }
}
